<template>
	<view class="login-container">
		<!-- 顶部标题 -->
		<view class="header">
			<image class="logo" src="/static/logo.png"></image>
			<text class="title">智慧园区运营</text>
			<text class="subtitle">便捷服务 · 智慧管理</text>
		</view>
		
		<!-- 切换标签 -->
		<view class="tab-container">
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'login' }" 
				@click="switchTab('login')"
			>
				登录
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'register' }" 
				@click="switchTab('register')"
			>
				注册
			</view>
		</view>
		
		<!-- 登录表单 -->
		<view v-if="activeTab === 'login'" class="form-container">
			<view class="input-group">
				<text class="label">手机号码</text>
				<input class="input" type="number" v-model="loginForm.phone" placeholder="请输入手机号码" maxlength="11" />
				<text class="error-tip" v-if="errors.loginPhone">{{errors.loginPhone}}</text>
			</view>
			<view class="input-group">
				<text class="label">密码</text>
				<input class="input" type="password" v-model="loginForm.password" placeholder="请输入密码" />
				<text class="error-tip" v-if="errors.loginPassword">{{errors.loginPassword}}</text>
			</view>
			<view class="forget-password" @click="forgetPassword">忘记密码?</view>
			<button class="submit-btn" :disabled="isSubmitting" @click="handleLogin">
				<text v-if="!isSubmitting">登录</text>
				<text v-else>登录中...</text>
			</button>
			
			<!-- 游客模式入口 -->
			<view class="guest-mode" @click="enterGuestMode">
				<text class="guest-text">游客模式</text>
				<text class="guest-desc">无需登录，体验部分功能</text>
			</view>
		</view>
		
		<!-- 注册表单 -->
		<view v-if="activeTab === 'register'" class="form-container">
			<view class="input-group">
				<text class="label">手机号码</text>
				<input class="input" type="number" v-model="registerForm.phone" placeholder="请输入手机号码" maxlength="11" />
				<text class="error-tip" v-if="errors.registerPhone">{{errors.registerPhone}}</text>
			</view>
			<view class="input-group">
				<text class="label">姓名</text>
				<input class="input" type="text" v-model="registerForm.name" placeholder="请输入姓名" />
				<text class="error-tip" v-if="errors.name">{{errors.name}}</text>
			</view>
			<view class="input-group verification-code">
				<text class="label">验证码</text>
				<input class="input" type="number" v-model="registerForm.code" placeholder="请输入验证码" maxlength="6" />
				<button class="code-btn" :disabled="isSending" @click="sendCode">
					{{ isSending ? `${countdown}s后重新获取` : '获取验证码' }}
				</button>
				<text class="error-tip" v-if="errors.code">{{errors.code}}</text>
			</view>
			<view class="input-group">
				<text class="label">密码</text>
				<input class="input" type="password" v-model="registerForm.password" placeholder="请设置密码" />
				<text class="error-tip" v-if="errors.password">{{errors.password}}</text>
			</view>
			<view class="input-group">
				<text class="label">确认密码</text>
				<input class="input" type="password" v-model="registerForm.confirmPassword" placeholder="请确认密码" />
				<text class="error-tip" v-if="errors.confirmPassword">{{errors.confirmPassword}}</text>
			</view>
			<button class="submit-btn" :disabled="isSubmitting" @click="handleRegister">
				<text v-if="!isSubmitting">注册</text>
				<text v-else>注册中...</text>
			</button>
			
			<!-- 游客模式入口（注册页也显示） -->
			<view class="guest-mode" @click="enterGuestMode">
				<text class="guest-text">游客模式</text>
				<text class="guest-desc">无需登录，体验部分功能</text>
			</view>
		</view>
		
		<!-- 底部协议 -->
		<view class="agreement">
			<checkbox :checked="isAgree" @click="isAgree = !isAgree" style="transform:scale(0.7)" />
			<text class="agreement-text">
				我已阅读并同意 <text class="link" @click="openAgreement">《用户协议》</text> 和 <text class="link" @click="openPrivacy">《隐私政策》</text>
			</text>
		</view>
	</view>
</template>

<script>
import { login, register } from '@/api/auth.js'

export default {
	data() {
		return {
			activeTab: 'login',
			isAgree: true,
			isSending: false,
			isSubmitting: false,
			countdown: 60,
			timer: null,
			loginForm: {
				phone: '',
				password: ''
			},
			registerForm: {
				phone: '',
				code: '',
				password: '',
				confirmPassword: '',
				name: ''
			},
			errors: {
				loginPhone: '',
				loginPassword: '',
				registerPhone: '',
				code: '',
				password: '',
				confirmPassword: '',
				name: ''
			}
		}
	},
	onLoad() {
		// 页面加载时执行
		// 这里不再检查登录状态，避免与App.vue中的跳转冲突
		console.log('登录页面加载')
	},
	methods: {
		// 重置错误信息
		resetErrors() {
			this.errors = {
				loginPhone: '',
				loginPassword: '',
				registerPhone: '',
				code: '',
				password: '',
				confirmPassword: '',
				name: ''
			}
		},
		
		// 切换标签
		switchTab(tab) {
			this.activeTab = tab
			this.resetErrors() // 切换标签时重置错误信息
		},
		
		// 验证手机号
		validatePhone(phone, field) {
			if (!phone) {
				this.errors[field] = '请输入手机号码'
				return false
			}
			if (!/^1[3-9]\d{9}$/.test(phone)) {
				this.errors[field] = '请输入正确的手机号码'
				return false
			}
			return true
		},
		
		// 发送验证码
		sendCode() {
			// 重置错误信息
			this.errors.registerPhone = ''
			this.errors.code = ''
			
			// 验证手机号
			if (!this.validatePhone(this.registerForm.phone, 'registerPhone')) {
				return
			}
			
			// 模拟发送验证码
			this.isSending = true
			this.countdown = 60
			this.timer = setInterval(() => {
				this.countdown--
				if (this.countdown <= 0) {
					clearInterval(this.timer)
					this.isSending = false
				}
			}, 1000)
			
			// 这里添加实际发送验证码的API调用
			uni.showToast({
				title: '验证码已发送',
				icon: 'success'
			})
		},
		
		// 处理登录
		async handleLogin() {
			// 重置错误信息
			this.resetErrors()
			
			// 表单验证
			let isValid = true
			
			if (!this.validatePhone(this.loginForm.phone, 'loginPhone')) {
				isValid = false
			}
			
			if (!this.loginForm.password) {
				this.errors.loginPassword = '请输入密码'
				isValid = false
			}
			
			if (!this.isAgree) {
				uni.showToast({
					title: '请同意用户协议和隐私政策',
					icon: 'none'
				})
				return
			}
			
			if (!isValid) return
			
			// 显示加载状态
			this.isSubmitting = true
			
			try {
				// 调用登录API
				console.log('发送登录请求:', {
					phone: this.loginForm.phone,
					username: this.loginForm.phone,
					password: this.loginForm.password
				})
				
				const response = await login({
					phone: this.loginForm.phone,  // 使用手机号作为phone参数
					username: this.loginForm.phone,  // 同时也发送username参数作为备份
					password: this.loginForm.password
				})
				
				console.log('登录响应详情:', response)
				
				// 保存token
				if (response.access && response.refresh) {
					uni.setStorageSync('token', response.access)
					uni.setStorageSync('refreshToken', response.refresh)
					
					// 获取用户信息并保存
					// 使用后端返回的用户信息，如果没有则使用手机号作为用户名
					uni.setStorageSync('userInfo', {
						phone: this.loginForm.phone,
						userType: 'registered',
						userName: response.userName || this.loginForm.phone, // 使用后端返回的用户名或手机号
						userId: response.userId || ('user_' + Date.now()) // 使用后端返回的用户ID或生成临时ID
					})
					uni.setStorageSync('hasLogin', true)
					
					uni.showToast({
						title: '登录成功',
						icon: 'success'
					})
					
					// 跳转到首页
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}, 1500)
				} else {
					// 检查是否有其他格式的响应
					if (response.code === 200 && response.message === '登录成功') {
						// 尝试从response中提取token
						const token = response.token || response.access || '';
						const refreshToken = response.refreshToken || response.refresh || '';
						
						if (token) {
							uni.setStorageSync('token', token)
							if (refreshToken) {
								uni.setStorageSync('refreshToken', refreshToken)
							}
							
							// 保存用户信息
							uni.setStorageSync('userInfo', {
								phone: this.loginForm.phone,
								userType: 'registered',
								userName: response.userName || this.loginForm.phone,
								userId: response.userId || ('user_' + Date.now())
							})
							uni.setStorageSync('hasLogin', true)
							
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							})
							
							// 跳转到首页
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/index/index'
								})
							}, 1500)
							return
						}
					}
					
					uni.showToast({
						title: '登录失败，请检查用户名和密码',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('登录失败:', error)
				
				// 显示登录失败的提示信息
				let errorMessage = '登录失败';
				if (error && error.detail) {
					errorMessage = error.detail;
				} else if (error && error.message) {
					errorMessage = error.message;
				}
				
				uni.showToast({
					title: errorMessage,
					icon: 'none',
					duration: 2000
				})
				
				// 移除自动使用测试账号登录的功能
				this.isSubmitting = false;
			} finally {
				this.isSubmitting = false
			}
		},
		
		// 处理注册
		async handleRegister() {
			// 重置错误信息
			this.resetErrors()
			
			// 表单验证
			let isValid = true
			
			if (!this.validatePhone(this.registerForm.phone, 'registerPhone')) {
				isValid = false
			}
			
			if (!this.registerForm.name) {
				this.errors.name = '请输入姓名'
				isValid = false
			}
			
			if (!this.registerForm.code) {
				this.errors.code = '请输入验证码'
				isValid = false
			}
			
			if (!this.registerForm.password) {
				this.errors.password = '请设置密码'
				isValid = false
			} else if (this.registerForm.password.length < 6) {
				this.errors.password = '密码长度不能少于6位'
				isValid = false
			}
			
			if (!this.registerForm.confirmPassword) {
				this.errors.confirmPassword = '请确认密码'
				isValid = false
			} else if (this.registerForm.confirmPassword !== this.registerForm.password) {
				this.errors.confirmPassword = '两次输入的密码不一致'
				isValid = false
			}
			
			if (!this.isAgree) {
				uni.showToast({
					title: '请同意用户协议和隐私政策',
					icon: 'none'
				})
				return
			}
			
			if (!isValid) return
			
			// 显示加载状态
			this.isSubmitting = true
			
			try {
				// 调用注册API
				const response = await register({
					username: this.registerForm.phone,
					password: this.registerForm.password,
					phone: this.registerForm.phone,
					name: this.registerForm.name,
				})
				
				// 注册成功
				uni.showToast({
					title: '注册成功，请登录',
					icon: 'success'
				})
				
				// 切换到登录标签，并预填写手机号
				this.loginForm.phone = this.registerForm.phone
				this.switchTab('login')
				
			} catch (error) {
				console.error('注册失败:', error)
				
				// 显示注册失败的提示信息
				let errorMessage = '注册失败';
				if (error && error.detail) {
					errorMessage = error.detail;
				}
				
				uni.showToast({
					title: errorMessage,
					icon: 'none',
					duration: 2000
				})
			} finally {
				this.isSubmitting = false
			}
		},
		
		// 进入游客模式
		async enterGuestMode() {
			if (!this.isAgree) {
				uni.showToast({
					title: '请同意用户协议和隐私政策',
					icon: 'none'
				})
				return
			}
			
			// 显示加载状态
			this.isSubmitting = true
			
			try {
				// 调用游客登录API
				const response = await login({
					phone: 'guest',
					username: 'guest',
					password: 'guest'
				})
				
				// 保存token
				if (response.access && response.refresh) {
					uni.setStorageSync('token', response.access)
					uni.setStorageSync('refreshToken', response.refresh)
					
					// 设置游客用户信息
					uni.setStorageSync('userInfo', {
						phone: 'guest',
						userType: 'guest',
						userName: '游客',
						userId: 'guest_' + Date.now()
					})
					uni.setStorageSync('hasLogin', true)
					
					uni.showToast({
						title: '正在进入游客模式',
						icon: 'loading',
						success: () => {
							setTimeout(() => {
								// 跳转到首页
								uni.reLaunch({
									url: '/pages/index/index'
								})
							}, 1000)
						}
					})
				} else {
					uni.showToast({
						title: '游客模式进入失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('游客模式进入失败:', error)
				
				// 显示失败提示信息
				let errorMessage = '游客模式暂时不可用';
				if (error && error.detail) {
					errorMessage = error.detail;
				}
				
				uni.showToast({
					title: errorMessage,
					icon: 'none',
					duration: 2000
				})
			} finally {
				this.isSubmitting = false
			}
		},
		
		// 忘记密码
		forgetPassword() {
			uni.showToast({
				title: '忘记密码功能开发中',
				icon: 'none'
			})
		},
		
		// 打开用户协议
		openAgreement() {
			uni.showToast({
				title: '用户协议页面开发中',
				icon: 'none'
			})
		},
		
		// 打开隐私政策
		openPrivacy() {
			uni.showToast({
				title: '隐私政策页面开发中',
				icon: 'none'
			})
		}
	},
	// 组件销毁时清除定时器
	beforeUnmount() {
		if (this.timer) {
			clearInterval(this.timer)
		}
	}
}
</script>

<style>
.login-container {
	padding: 40rpx;
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #FFFFFF;
}

.header {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 60rpx;
	margin-top: 40rpx;
}

.logo {
	width: 160rpx;
	height: 160rpx;
	margin-bottom: 20rpx;
}

.title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 10rpx;
}

.subtitle {
	font-size: 24rpx;
	color: #666;
}

.tab-container {
	display: flex;
	justify-content: center;
	margin-bottom: 40rpx;
}

.tab-item {
	padding: 20rpx 40rpx;
	font-size: 32rpx;
	position: relative;
	color: #666;
}

.tab-item.active {
	color: #007AFF;
	font-weight: bold;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 60rpx;
	height: 4rpx;
	background-color: #007AFF;
}

.form-container {
	width: 100%;
}

.input-group {
	margin-bottom: 30rpx;
	position: relative;
}

.label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
	display: block;
}

.input {
	width: 100%;
	height: 90rpx;
	background-color: #F8F8F8;
	border-radius: 45rpx;
	padding: 0 30rpx;
	font-size: 28rpx;
	box-sizing: border-box;
}

.error-tip {
	font-size: 24rpx;
	color: #FF5151;
	margin-top: 6rpx;
	padding-left: 20rpx;
}

.verification-code {
	position: relative;
}

.code-btn {
	position: absolute;
	right: 10rpx;
	top: 45rpx;
	background-color: #007AFF;
	color: white;
	border: none;
	border-radius: 45rpx;
	font-size: 24rpx;
	padding: 0 20rpx;
	height: 70rpx;
	line-height: 70rpx;
}

.code-btn[disabled] {
	background-color: #CCCCCC;
}

.forget-password {
	text-align: right;
	font-size: 24rpx;
	color: #007AFF;
	margin-bottom: 40rpx;
}

.submit-btn {
	width: 100%;
	height: 90rpx;
	background-color: #007AFF;
	color: white;
	border-radius: 45rpx;
	font-size: 32rpx;
	margin-top: 20rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.submit-btn[disabled] {
	background-color: #CCCCCC;
}

/* 游客模式样式 */
.guest-mode {
	margin-top: 40rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 20rpx;
	border: 1px dashed #DDDDDD;
	border-radius: 10rpx;
	background-color: #F9F9F9;
}

.guest-text {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 5rpx;
}

.guest-desc {
	font-size: 22rpx;
	color: #999;
}

.agreement {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 40rpx;
}

.agreement-text {
	font-size: 24rpx;
	color: #999;
}

.link {
	color: #007AFF;
}
</style> 